/**
 * @description  费用维护
 * @author shenhong
 */
import React, { PureComponent } from 'react';
import { message } from 'antd';
import { connect } from 'dva';
import { PrimaryC, PrimaryGhostC, FirstHeaderC, FormGroup, DATA_ENTRY, FixedButtonC } from '../../../comps';
import costValue from '../../../utils/enumeratedValues/costValue';
import style from './index.less';

class AddCost extends PureComponent {
  constructor() {
    super();
    this.state = {
      id: '', //是否为编辑
      exchangecode: '113', //交易平台，默认银行间
      secType: '', //证券类别
      calculationmethod: '', //费用计算方式
      ismaxfee: false, //是否最高费用 0--1
      isminfee: false, //是否最低费用 0--1
      ispreferential: false, //是否优惠 0--1
      pricemin: undefined,
      pricemax: undefined,
      maxMoney: undefined,
      minMoney: undefined,
    };
  }

  componentDidMount() {
    const { itemInfo } = this.props;
    if (itemInfo && itemInfo.id) {
      this.setState({
        id: itemInfo.id,
        exchangecode: itemInfo.exchangecode,
        secType: itemInfo.sectype,
        calculationmethod: itemInfo.calculationmethod,
        maxMoney: itemInfo.maxMoney,
        minMoney: itemInfo.minMoney,
        pricemin: itemInfo.pricemin,
        pricemax: itemInfo.pricemax,
        ismaxfee: itemInfo.ismaximumfee == '1' ? true : false,
        isminfee: itemInfo.isminimumfee == '1' ? true : false,
        ispreferential: itemInfo.ispreferential == '1' ? true : false,
      });
      let fieldsVlues = {
        calculationmethod: itemInfo.calculationmethod, //费用计算方式
        classification: itemInfo.classification, //分类
        costtype: itemInfo.costtype, //费用类型
        discountRatio: itemInfo.discountRatio ? itemInfo.discountRatio * 100 : itemInfo.discountRatio, //优惠比例
        exchangecode: itemInfo.exchangecode, //交易市场
        fundnature: itemInfo.fundnature ? itemInfo.fundnature.split(',') : undefined, //基金性质
        groupid: itemInfo.groupid,
        ismaximumfee: itemInfo.ismaximumfee ? itemInfo.ismaximumfee : undefined, //是否有最高费用
        isminimumfee: itemInfo.isminimumfee ? itemInfo.isminimumfee : undefined, //是否有最低费用
        ispreferential: itemInfo.ispreferential ? itemInfo.ispreferential : undefined, //是否优惠
        maxMoney: itemInfo.maxMoney, //最高费用
        minMoney: itemInfo.minMoney, //最低费用
        orderside: itemInfo.orderside, //交易方向
        pledgedbondsamount: itemInfo.pledgedbondsamount || undefined, //质押券个数
        portfolioid: itemInfo.portfolioid,
        price: itemInfo.price, //金额
        pricemax: itemInfo.pricemax, //交易金额区间最大
        pricemin: itemInfo.pricemin, //交易金额区间最小
        productid: itemInfo.productid,
        rate: itemInfo.rate ? itemInfo.rate * 1000 : itemInfo.rate, //比例
        sectype: itemInfo.sectype, //证券类别
        sectypeii: itemInfo.sectypeii ? itemInfo.sectypeii.split(',') : undefined, //证券子类
        istransaction: itemInfo.istransaction ? itemInfo.istransaction : undefined, //是否逐笔结算
        timeLimit: itemInfo.timeLimit, //期限
        trademarket: itemInfo.trademarket, //交易平台
      };
      this.AddCost.props.form.setFieldsValue(fieldsVlues);
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}

  //产品组select变化
  productGroupChange = (e) => {
    if (e) {
      let fieldsVlues = {
        productid: undefined,
        portfolioid: undefined,
      };
      this.AddCost.props.form.setFieldsValue(fieldsVlues);
    }
  };

  //产品select变化
  productChange = (e) => {
    if (e) {
      let fieldsVlues = {
        groupid: undefined,
        portfolioid: undefined,
      };
      this.AddCost.props.form.setFieldsValue(fieldsVlues);
    }
  };

  //组合select变化
  portfolioidChange = (e) => {
    if (e) {
      let fieldsVlues = {
        groupid: undefined,
        productid: undefined,
      };
      this.AddCost.props.form.setFieldsValue(fieldsVlues);
    }
  };

  //交易市场改变时
  changeCode = (e) => {
    if (e) {
      this.setState({
        exchangecode: e.value,
      });
      let fieldsVlues = {
        trademarket: undefined,
        costtype: undefined,
      };
      this.AddCost.props.form.setFieldsValue(fieldsVlues);
    }
  };

  //证券类别改变时
  sectype = (e) => {
    if (e) {
      this.setState({
        secType: e,
      });
      let fieldsVlues = {
        sectypeii: undefined,
        fundnature: undefined,
        timeLimit: undefined,
        pledgedbondsamount: undefined,
      };
      this.AddCost.props.form.setFieldsValue(fieldsVlues);
    }
  };

  //费用计算方式改变时
  changeMethod = (e) => {
    if (e) {
      this.setState({
        calculationmethod: e,
      });
      let fieldsVlues = {
        rate: undefined,
        price: undefined,
      };
      this.AddCost.props.form.setFieldsValue(fieldsVlues);
    }
  };

  //比较最低最高费用
  compareMoney = (type) => {
    const { pricemin, pricemax, maxMoney, minMoney } = this.state;
    let fieldsVlues;
    if (type == 'pricemin' || type == 'pricemax') {
      if (pricemin && pricemax) {
        if (pricemin > pricemax) {
          message.error('最小交易金额区间需小于最大交易金额区间');
          if (type == 'pricemin') {
            fieldsVlues = {
              pricemin: undefined,
            };
            this.setState({
              pricemin: undefined,
            });
          } else {
            fieldsVlues = {
              pricemax: undefined,
            };
            this.setState({
              pricemax: undefined,
            });
          }
        }
      }
    }
    if (type == 'maxMoney' || type == 'minMoney') {
      if (maxMoney && minMoney) {
        if (minMoney > maxMoney) {
          message.error('最低费用需小于最高费用');
          if (type == 'maxMoney') {
            fieldsVlues = {
              maxMoney: undefined,
            };
            this.setState({
              maxMoney: undefined,
            });
          } else {
            fieldsVlues = {
              minMoney: undefined,
            };
            this.setState({
              minMoney: undefined,
            });
          }
        }
      }
    }
    this.AddCost.props.form.setFieldsValue(fieldsVlues);
  };

  //返回表格页面
  backMain = () => {
    this.props.changeEdit();
  };

  // 添加确认btn
  sureBtn = () => {
    const { dispatch } = this.props;
    let calculateData = this.AddCost.getFormGroupData(); //获取计算数据
    if (calculateData) {
      if (calculateData.groupid == undefined && calculateData.productid == undefined && calculateData.portfolioid == undefined) {
        message.error('请将数据填写完整！（产品组、产品、组合必选一个）');
        return;
      }
      if (calculateData.sectypeii && calculateData.sectypeii.length) {
        calculateData.sectypeii = calculateData.sectypeii.toString();
      }
      if (calculateData.fundnature && calculateData.fundnature.length) {
        calculateData.fundnature = calculateData.fundnature.toString();
      }
    } else {
      message.error('请将数据填写完整！');
      return;
    }
    if (calculateData.rate) {
      calculateData.rate = calculateData.rate / 1000;
    }
    if (calculateData.discountRatio) {
      calculateData.discountRatio = calculateData.discountRatio / 100;
    }
    if (this.state.id) {
      calculateData.id = this.state.id;
      dispatch({
        type: 'costMaintainM/editCost',
        payload: calculateData,
        callback: (res) => {
          message.success('编辑成功');
          this.props.changeEdit(true);
        },
      });
    } else {
      dispatch({
        type: 'costMaintainM/addCost',
        payload: calculateData,
        callback: (res) => {
          message.success('添加成功');
          this.props.changeEdit(true);
        },
      });
    }
  };

  render() {
    const {
      exchangecode,
      secType,
      calculationmethod,
      ismaxfee,
      isminfee,
      ispreferential,
      id,
      pricemin,
      pricemax,
      maxMoney,
      minMoney,
      priceminValue,
      pricemaxValue,
      maxMoneyValue,
      minMoneyValue,
    } = this.state;
    return (
      <div className={style.addCost}>
        <FixedButtonC
          topHtml={
            <>
              <FirstHeaderC title={id ? '费用维护-编辑' : '费用维护-新增'} />
              <FormGroup
                dataSource={[
                  {
                    dataIndex: 'classification',
                    title: '分类',
                    type: DATA_ENTRY.SELECT,
                    disabled: true,
                    dataSource: costValue.classification,
                    initialValue: '2',
                  },
                  { dataIndex: 'groupid', title: '产品组', type: DATA_ENTRY.PRODUCTGROUP, onChange: (e) => this.productGroupChange(e) },
                  { dataIndex: 'productid', title: '产品', type: DATA_ENTRY.PRODUCTLIST, onChange: (e) => this.productChange(e) },
                  { dataIndex: 'portfolioid', title: '组合', type: DATA_ENTRY.PRODUCTGROUPTREE, multiple: false, onChange: (e) => this.portfolioidChange(e) },
                  {
                    dataIndex: 'exchangecode',
                    title: '交易市场',
                    type: DATA_ENTRY.TRADINGMARKET,
                    rules: [{ required: true, message: '请选择' }],
                    marketType: ['jys', 'yhj'],
                    initialValue: '113',
                    onChange: (e) => this.changeCode(e),
                  },
                  {
                    dataIndex: 'trademarket',
                    title: '交易平台',
                    disabled: exchangecode == '113',
                    type: DATA_ENTRY.SELECT,
                    rules: [{ required: exchangecode != '113', message: '请输入' }],
                    dataSource: exchangecode == '101' ? costValue.market.sjsmarket : exchangecode == '105' ? costValue.market.szjysmarket : [],
                  },
                  {
                    dataIndex: 'costtype',
                    title: '费用类型',
                    type: DATA_ENTRY.SELECT,
                    rules: [{ required: true, message: '请输入' }],
                    dataSource: exchangecode == '113' ? costValue.costtype.yhjcosttype : costValue.costtype.sjsAndsjscosttype,
                  },
                  {
                    dataIndex: 'sectype',
                    title: '证券类别',
                    type: DATA_ENTRY.SELECT,
                    rules: [{ required: true, message: '请输入' }],
                    dataSource: costValue.costsectype,
                    onChange: (e) => this.sectype(e),
                  },
                  secType == 'bond'
                    ? {
                        dataIndex: 'sectypeii',
                        title: '证券子类',
                        type: DATA_ENTRY.WINBONDTYPE,
                        showCheckedStrategy: 'SHOW_CHILD',
                      }
                    : {
                        dataIndex: 'sectypeii',
                        title: '证券子类',
                        isMultiple: true,
                        type: DATA_ENTRY.SELECT,
                        disabled: !costValue.sectypeii[secType],
                        dataSource: costValue.sectypeii[secType],
                      },
                  {
                    dataIndex: 'fundnature',
                    title: '基金性质',
                    disabled: secType != 'fund',
                    type: DATA_ENTRY.SELECT,
                    isMultiple: true,
                    rules: [{ required: secType == 'fund', message: '请输入' }],
                    dataSource: costValue.fundnature,
                  },
                  {
                    dataIndex: 'orderside',
                    title: '交易方向',
                    type: DATA_ENTRY.SELECT,
                    disabled: true,
                    dataSource: costValue.orderside,
                  },
                  {
                    dataIndex: 'timeLimit',
                    title: '期限',
                    type: DATA_ENTRY.SELECT,
                    disabled: secType != 'hg',
                    rules: [{ required: secType == 'hg', message: '请输入' }],
                    dataSource: costValue.hgTimeLimit,
                  },
                  {
                    dataIndex: 'pledgedbondsamount',
                    title: '质押券个数',
                    disabled: secType != 'hg',
                    type: DATA_ENTRY.SELECT,
                    rules: [{ required: secType == 'hg', message: '请输入' }],
                    dataSource: costValue.pledgeAmount,
                  },
                  {
                    dataIndex: 'pricemin',
                    title: '交易金额区间最小',
                    type: DATA_ENTRY.INPUTNUMBER,
                    unit: '元',
                    min: 0,
                    precision: 2,
                    onChange: (e) => {
                      this.setState({
                        pricemin: e,
                      });
                    },
                    onBlur: () => this.compareMoney('pricemin'),
                  },
                  {
                    dataIndex: 'pricemax',
                    title: '交易金额区间最大',
                    type: DATA_ENTRY.INPUTNUMBER,
                    unit: '元',
                    min: 0,
                    precision: 2,
                    onChange: (e) => {
                      this.setState({
                        pricemax: e,
                      });
                    },
                    onBlur: () => this.compareMoney('pricemax'),
                  },
                  {
                    dataIndex: 'calculationmethod',
                    title: '费用计算方式',
                    type: DATA_ENTRY.SELECT,
                    rules: [{ required: true, message: '请输入' }],
                    dataSource: costValue.calculationmethod,
                    onChange: (e) => this.changeMethod(e),
                  },
                  {
                    dataIndex: 'rate',
                    title: '比例',
                    type: DATA_ENTRY.INPUTNUMBER,
                    disabled: calculationmethod != 'money',
                    rules: [{ required: calculationmethod == 'money', message: '请输入' }],
                    unit: '‰',
                    min: 0,
                    precision: 6,
                  },
                  {
                    dataIndex: 'price',
                    title: '金额',
                    type: DATA_ENTRY.INPUTNUMBER,
                    disabled: calculationmethod != 'count',
                    rules: [{ required: calculationmethod == 'count', message: '请输入' }],
                    unit: '元/笔',
                    min: 0,
                    precision: 2,
                  },
                  {
                    dataIndex: 'ispreferential',
                    title: '是否优惠',
                    type: DATA_ENTRY.SELECT,
                    isTrueFalseJudge: true,
                    initialValue: '0',
                    onChange: (e) => {
                      if (e != 1) {
                        let fieldsVlues = {
                          discountRatio: undefined,
                        };
                        this.AddCost.props.form.setFieldsValue(fieldsVlues);
                      }
                      this.setState({
                        ispreferential: e == 1 ? true : false,
                      });
                    },
                  },
                  {
                    dataIndex: 'discountRatio',
                    title: '优惠比例',
                    disabled: !ispreferential,
                    type: DATA_ENTRY.INPUTNUMBER,
                    rules: [{ required: ispreferential, message: '请输入' }],
                    min: 0,
                    unit: '%',
                    precision: 2,
                  },
                  {
                    dataIndex: 'ismaximumfee',
                    title: '是否有最高费用',
                    type: DATA_ENTRY.SELECT,
                    isTrueFalseJudge: true,
                    onChange: (e) => {
                      if (e != 1) {
                        let fieldsVlues = {
                          maxMoney: undefined,
                        };
                        this.AddCost.props.form.setFieldsValue(fieldsVlues);
                      }
                      this.setState({
                        ismaxfee: e == 1 ? true : false,
                      });
                    },
                  },
                  {
                    dataIndex: 'maxMoney',
                    title: '最高费用',
                    type: DATA_ENTRY.INPUTNUMBER,
                    rules: [{ required: ismaxfee, message: '请输入' }],
                    unit: '元',
                    min: 0,
                    precision: 2,
                    onChange: (e) => {
                      this.setState({
                        maxMoney: e,
                      });
                    },
                    onBlur: () => this.compareMoney('maxMoney'),
                    disabled: !ismaxfee,
                  },
                  {
                    dataIndex: 'isminimumfee',
                    title: '是否有最低费用',
                    type: DATA_ENTRY.SELECT,
                    isTrueFalseJudge: true,
                    onChange: (e) => {
                      if (e != 1) {
                        let fieldsVlues = {
                          minMoney: undefined,
                        };
                        this.AddCost.props.form.setFieldsValue(fieldsVlues);
                      }
                      this.setState({
                        isminfee: e == 1 ? true : false,
                      });
                    },
                  },
                  {
                    dataIndex: 'minMoney',
                    title: '最低费用',
                    type: DATA_ENTRY.INPUTNUMBER,
                    rules: [{ required: isminfee, message: '请输入' }],
                    unit: '元',
                    min: 0,
                    precision: 2,
                    onChange: (e) => {
                      this.setState({
                        minMoney: e,
                      });
                    },
                    onBlur: () => this.compareMoney('minMoney'),
                    disabled: !isminfee,
                  },
                  { dataIndex: 'istransaction', title: '是否逐笔结算', type: DATA_ENTRY.SELECT, isTrueFalseJudge: true },
                ]}
                onRef={(ref) => {
                  this.AddCost = ref;
                }}
              />
            </>
          }
          bottomHtml={
            <div style={{ width: '100%', textAlign: 'right' }}>
              <PrimaryGhostC title={'取消'} onClick={this.backMain} style={{ marginRight: '20px' }}></PrimaryGhostC>
              <PrimaryC title={'确定'} onClick={this.sureBtn}></PrimaryC>
            </div>
          }
        />
      </div>
    );
  }
}
export default connect(({ costMaintainM }) => ({
  costMaintainM,
}))(AddCost);
